package com.linglan.common.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.concurrent.TimeUnit;

@Slf4j
public class RedisUtil {
	
    private RedisTemplate<String,String> redisTemplate;

    public void setRedisTemplate(RedisTemplate<String, String> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    //以下为业务调用

    /**
     * 添加缓存
     * @param key
     * @param value
     * @param timeout
     */
    public void set(String key, String value, long timeout) {
        try {
            this.redisTemplate.opsForValue().set(key,value,timeout, TimeUnit.SECONDS);
        } catch (Exception e) {
            log.error("set 出错 key={} value={} timeout={}", key, value, timeout, e);
        }
    }

    /**
     * 查询缓存
     * @param key
     * @return
     */
    public String get(String key) {
        try {
            return this.redisTemplate.opsForValue().get(key);
        } catch (Exception e) {
            log.error("get 出错 key={} ", key, e);
        }
        return null;
    }


    /**
     * 删除缓存
     * @param key
     */
    public void deleteKey(String key) {
        try {
            this.redisTemplate.delete(key);
        } catch (Exception e) {
            log.error("deleteKey 出错 key={} ", key, e);
        }
    }

}